package cn.edu.scnu.springbootcinema.service;

import cn.edu.scnu.springbootcinema.entity.User;
import cn.edu.scnu.springbootcinema.entity.UserFavorite;
import cn.edu.scnu.springbootcinema.mapper.UserFavoriteMapper;
import cn.edu.scnu.springbootcinema.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    private UserMapper userMapper;
    private RedisTemplate<String, Object> redisTemplate;

    private UserFavoriteMapper userFavoriteMapper;

    public UserService(UserMapper userMapper, RedisTemplate<String, Object> redisTemplate, UserFavoriteMapper userFavoriteMapper) {
        this.userMapper = userMapper;
        this.redisTemplate = redisTemplate;
        this.userFavoriteMapper = userFavoriteMapper;
    }

    public boolean register(User user) {
        return userMapper.insert(user) > 0;
    }

    public User login(String email, String password) {
        String redisKey = "user:login:" + email;
        // 先查Redis
        User user = (User) redisTemplate.opsForValue().get(redisKey);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        user=userMapper.selectById(email);
        if(user!=null&&user.getPassword().equals(password)) {
            redisTemplate.opsForValue().set(redisKey, user, 1, TimeUnit.DAYS);
            return user;
        }else
            return null;
    }


    public boolean isVipUser(Integer userId) {
        User user = userMapper.selectById(userId);
        return user != null && user.getVipDuration() == 1;
    }

    public void likeMovie(Integer userId, Integer movieId) {
        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUserId(userId);
        userFavorite.setMovieId(movieId);
        userFavorite.setCreateTime(LocalDateTime.now());
        userFavoriteMapper.insert(userFavorite);
    }

    public void dislikeMovie(Integer userId, Integer movieId) {
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("movie_id", movieId);
        userFavoriteMapper.delete(queryWrapper);
    }
}